package com.laoyao.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.laoyao.comm.config.CrossOrigin;
import com.laoyao.comm.model.PersonalLetter;
import com.laoyao.util.DateUtil;
import com.laoyao.validate.LetterValidate;

@CrossOrigin
public class PersonalLetterController extends Controller {
	//发送私信
	@Before(LetterValidate.class)
	public void send(){
		PersonalLetter p = getBean(PersonalLetter.class,"");
		p.setOwnerId(p.getSid());
		p.setGuestId(p.getRid());
		p.setTime(DateUtil.getTime());//自己的私信
		p.save();
		p.setOwnerId(p.getRid()); //对方的私信
		p.setGuestId(p.getSid());
		//PersonalLetter p2 = new PersonalLetter();
		p.setId(null);
		//p2=p;
		renderJson("success",p.save());
	}
	//返回私信列表
	public void list(){
		String id = getPara("id");
		String sql = "select a.*,b.userName,b.photo,max(a.time),COUNT(isRead=0 or null) unread "
				+ " from v_personal_letter a ,v_user b where a.guestId = b.id and a.ownerId=? GROUP BY a.guestId order by a.time desc";
		renderJson("list",Db.find(sql,id));
	}
	//返回聊天记录
	public void talkList(){
		String id = getPara("id");
		String gid = getPara("gid");
		String sql="select a.*,b.userName,b.photo from v_personal_letter a ,v_user b where a.guestId = b.id and a.ownerId=? and a.guestId=?";
		String upsql="update v_personal_letter set isRead=1 where ownerId=? and guestId=?";
		Db.update(upsql,id,gid);
		renderJson("list",Db.find(sql,id,gid));
	}
	public void del(){
		String id = getPara("id");
		String gid = getPara("gid");
		
		String sql = "delete from v_personal_letter where ownerId=? and guestId=?";
		renderJson("success",Db.update(sql,id,gid));
		
	}
	
	public void allUnread(){
		String ownerId = getPara("ownerId");
		String sql ="select count(*) num from v_personal_letter where ownerId=? and rid=? and isRead=0";
		renderJson("num",Db.findFirst(sql,ownerId,ownerId).get("num"));
	}
	
	public void read(){
		String ownerId = getPara("ownerId");
		String sql  = "update v_personal_letter set isRead=1 where ownerId=?";
		renderJson("success",Db.update(sql,ownerId));
	}
	
}
